package com.bci.pwtz.servlet;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.bci.pwtz.service.impl.VerifyCodeServiceImpl;

/**
 * Servlet Filter implementation class UserAjaxSessionFilter
 */
public class UserAjaxSessionFilter implements Filter
{
    private static final Logger _logger = Logger.getLogger(VerifyCodeServiceImpl.class);
    private String[] excludeUrls;
    private String[] freeSuffixs;
    public UserAjaxSessionFilter()
    {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy()
    {
        // TODO Auto-generated method stub
    }
    private boolean isExclude(String url,String[] excludeUrls)
    {
        for(String s:excludeUrls)
        {
            if(url.indexOf(s) != -1)
                return true;
        }
        return false;
    }
    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    {
        HttpServletRequest req =  (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        String url = req.getRequestURI().toLowerCase();
        //开放访问后缀
        for(String freeSuffix : freeSuffixs){
        	if(url.endsWith(freeSuffix)){
        		chain.doFilter(request, response);
        		return;
        	}
        }
        
        if(!isExclude(url,excludeUrls))
        {
            if(req.getSession().getAttribute("user") == null||req.getSession().getAttribute("userId") == null)
            {
                resp.setHeader("SessionStatus", "SessionTimeout");  
                resp.sendRedirect("/pwtz/user/m/userflow.jsp"); 
                return;
            }
        }
        
        
        /*if(req.getHeader("x-requested-with") != null&& req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest"))
        {
            if(!isExclude(url,excludeUrls))
            {
                if(req.getSession().getAttribute("user") == null||req.getSession().getAttribute("userId") == null)
                {
                    resp.setHeader("SessionStatus", "SessionTimeout");  
                    response.getWriter().print("sessionOut");  
                    return;
                }
            }
        }*/
        chain.doFilter(request, response);
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException
    {
    	String freeSuffixStr = fConfig.getServletContext().getInitParameter("freeSuffix");
    	if(StringUtils.isBlank(freeSuffixStr))
    		freeSuffixs = new String[0];
        else
        	freeSuffixs = freeSuffixStr.split(",");
        
        if(_logger.isDebugEnabled())
        {
            String log = "UserAjaxSessionFilter,freeSuffixs:";
            _logger.debug(log+Arrays.toString(freeSuffixs));
        }
        
        String excludeUrlsStr = fConfig.getInitParameter("excludeUrls");
        if(StringUtils.isBlank(excludeUrlsStr))
            excludeUrls = new String[0];
        else
            excludeUrls = excludeUrlsStr.split(",");
        
        if(_logger.isDebugEnabled())
        {
            String log = "UserAjaxSessionFilter,excludeUrls:";
            for(String s : excludeUrls)
            {
                log+="["+s+"]";
            }
            _logger.debug(log);
        }
    }

}
